package scatter.common.rest.security;

import org.springframework.util.Assert;
import scatter.common.LoginUser;
import scatter.common.rest.tools.ThreadContextTool;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 当前登录用户工具类，方便在任何地方直接获取当前登录用户
 * 但尽量不要在 service 中过度使用，尽量保持方法调用登录用户参数传递
 * 注意：scatter 中暂不支持在线程池中直接调用
 * Created by yangwei
 * Created at 2020/10/13 14:57
 */
public class LoginUserTool {

    public static final String LOGIN_USER_SESSION_KEY = "login_user_session_key";
    
    public static String getLoginUserId(){
        return Optional.ofNullable(getLoginUser()).map(LoginUser::getId).orElse(null);
    }
    /**
     * 从thread中获取用户
     * @return
     */
    public static LoginUser getLoginUser() {
        return (LoginUser) ThreadContextTool.get(LOGIN_USER_SESSION_KEY);
    }
    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    public static LoginUser retrieveFromSession(HttpServletRequest request) {
        Assert.notNull(request,"request为空，请查检传入参数");
        return (LoginUser) request.getSession().getAttribute(LOGIN_USER_SESSION_KEY);
    }

    /**
     * 设置当前登录用户到session，一般登录成功后使用
     * @param user
     * @param request
     */
    public static void saveToSession(LoginUser user, HttpServletRequest request) {
        ThreadContextTool.put(LOGIN_USER_SESSION_KEY,user);
        request.getSession().setAttribute(LOGIN_USER_SESSION_KEY,user);
    }

    /**
     * 设置当前登录用户到threadContext，一般登录成功后使用
     * @param user
     */
    public static void saveToThreadContext(LoginUser user) {
        ThreadContextTool.put(LOGIN_USER_SESSION_KEY,user);
    }
}
